import { RootState } from '@/types/store'
import { useEffect } from 'react'
import { useDispatch, useSelector } from 'react-redux'
/**
 *
 * @param actionFn 异步action函数
 * @param stateName redux数据模块名
 * @returns
 */
export function useInitState<StateName extends keyof RootState>(
  actionFn: () => void,
  stateName: StateName
) {
  const dispatch = useDispatch()
  useEffect(() => {
    // 1. 分发异步action获取数据，存到redux
    dispatch<any>(actionFn())
  }, [dispatch, actionFn])
  // 2. 从redux获取数据
  const state = useSelector((state: RootState) => state[stateName])
  // 返回外部需要的数据
  return state
}
